import { Toast } from "vant";
import { Http } from "./HttpClient";


export class MapUtil {

  constructor() { }

  static target;
  static themeColor='#3676F5';//主题色
  static instance() {
    if (this.target == null) {
      this.target = new MapUtil()
    }
    return this.target;
  }
  loginedFlag = false;
  geocodingTask
  converTask

  // 逆地理编码
  getPositionNameByLngLat(lng, lat, block) {

    if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'vpn') {
      block && block('');
    }

    this.login(() => {
      if (this.geocodingTask == null) {
        this.geocodingTask = new epgis.GeocodingTask()
      }

      this.geocodingTask.getAddress({
        location: [lng, lat],
        coordtype: "gps"
      }).then(function (result) {
        block && block(result.formattedAddress)
      });
    });
  }

  //经纬度转换成三角函数中度分表形式。
  rad(d) {
    return d * Math.PI / 180.0;
  }

  // 获取两点间距离
  getDistance(slng, slat, dlng, dlat, block) {

    if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'vpn') {
      let radLat1 = this.rad(slat);
      let radLat2 = this.rad(dlat);
      let a = radLat1 - radLat2;
      let b = this.rad(slng) - this.rad(dlng);
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;// EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000; //输出为公里
      let dis = (s * 1000) + ''
      block && block(parseInt(dis));

      return;
    }

    this.login(() => {
      console.log("第1个经度：" + slng + " 纬度：" + slat);
      console.log("第2个经度：" + dlng + " 纬度：" + dlat);
      var distance = epgis.GeometryUtil.distance([slng,slat], [dlng,dlat]);
      console.log("底层计算距离：" + distance);
      block && block(parseInt(distance));
    })
  }
  convertCoord(lng, lat, block) {
    this.login(() => {
      // console.log("进入坐标转换")
      if (this.converTask == null) {
        // console.log("new epgis.ConvertTask() 开始")
        this.converTask = new epgis.ConvertTask()
        // console.log("new epgis.ConvertTask() 结束")
      }
      // console.log("坐标转换开始")
      this.converTask.convertCoord([[lng, lat]], {
        from: 1,
      }).then(function (result) {
        // console.log("坐标转换返回result："+result)
        block && block(result)
      })
    })

  }

  goNavi =async (lon, lat, block) => {  
    if (deviceReady == true) {
      // 外网应用
      if(process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'dlydt') {
        console.log("进入i国网导航");
        navigator.openSwitch.toBaiDu(null, async (msg)=> {
          if (msg == "101") { 
            await this.loadMapJs('a909ebff02c112d3d18da64d3d9afbdb','amap'); 
            AMap.convertFrom(lon + "," + lat, "baidu", function (meg, locations) {
              console.log(locations)
              if(locations.locations&&Array.isArray(locations.locations)){  
                
                navigator.openSwitch.toMap(null, function (data) {
                  Toast.fail("调用地图导航失败，请安装百度地图或者高德地图")
                }, locations.locations[0].lng, locations.locations[0].lat);
              }else{
                Toast.fail("请下载百度地图进行导航!")
              }
             
            });
          } else {
            console.log('返回' + msg);
          }
        }, lon, lat, "wgs84");
      }else if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == 'yixin') {
        console.log("进入闽电运检导航");
        await this.loadMapJs('D6qEY3jquov0bhxzeZ6Idu3za7Vv4uQ2'); 
        var gpsPoint = new BMap.Point(lon, lat);
        var pointArr = [];
        pointArr.push(gpsPoint);
        var convertor = new BMap.Convertor();
        convertor.translate(pointArr, 1, 5,async (bdData)=> {
          if (bdData.status === 0) {
            console.log("百度坐标转换成功");
            var lon = bdData.points[0].lng;
            var lat = bdData.points[0].lat;
            
            navigator.openSwitch.toBaiDu(null, async (msg)=> {
              if (msg == "101") { 
                await this.loadMapJs('a909ebff02c112d3d18da64d3d9afbdb','amap'); 
                AMap.convertFrom(lon + "," + lat, "baidu", function (meg, locations) {
                  console.log(locations)
                  if(locations.locations&&Array.isArray(locations.locations)){  
                    
                    navigator.openSwitch.toMap(null, function (data) {
                      Toast.fail("调用地图导航失败，请安装百度地图或者高德地图")
                    }, locations.locations[0].lng, locations.locations[0].lat);
                  }else{
                    Toast.fail("请下载百度地图进行导航!")
                  }
                 
                });
              } else {
                console.log('返回' + msg);
              }
            }, lon, lat);
          } else {
            Toast.fail("坐标转换失败!")
          }
        });
      } 
    } else {
      Toast.fail("努力加载中")
    }
  }
  //加载百度地图、高德地图JS
  loadMapJs(key,type='bmap') { 
    let url='';
    if(type=='bmap'){
      url=`https://api.map.baidu.com/api?v=3.0&ak=${key}`;
    }else if(type=='amap'){
      url=`https://webapi.amap.com/maps?v=1.4.15&key=${key}`;
    }
    const Map_URL = `${url}&callback=onMapCallback`;
    return new Promise((resolve, reject) => {
      // 如果已加载直接返回
      if (typeof window.AMap !== 'undefined'&&type=='amap') {
        resolve(true);
        return true;
      }
      if (typeof window.BMap !== 'undefined'&&type=='bmap') {
        resolve(true);
        return true;
      }
      console.log(type+':初始化地图脚本...'); 
     // 百度地图异步加载回调处理
      window.onMapCallback = function () {
        console.log(type+':地图脚本初始化成功...');
        resolve(true);
      };
      // 插入script脚本
      let scriptNode = document.createElement('script');
      scriptNode.setAttribute('type', 'text/javascript');
      scriptNode.setAttribute('src', Map_URL);
      document.body.appendChild(scriptNode);
    });
  }  
  login(block) {
    if (!this.loginedFlag) {
      epgis.tokenTask.login('1ab17373e9f53bd2b5051ea3778ea9ec', "1dc5701615a93f7bbc535785cbbe4618").then(() => {
        this.loginedFlag = true;
        block && block()
      });
    } else {
      block && block()
    }
  } 
  DDDToDMS(_data){
    let value = parseFloat(_data);
    let _d = Math.floor(value);//度
    let _m = Math.floor((value - _d) * 60);//分
    //let _s = Math.round((value - _d) * 3600 % 60);//秒 保留整数
    let _s =  parseFloat((value - _d) * 3600 % 60).toFixed(2);//精确小数点后面两位
    return _d+ '°' + _m + '\'' + _s + '"';
  } 
  DMSToDDD(_data){
    let du = _data.split("°")[0];
    let fen = _data.split("°")[1].split("'")[0];
    let miao = _data.split("°")[1].split("'")[1].split('"')[0];
    let res =Math.abs(du) +(Math.abs(fen)/60 + Math.abs(miao)/3600);
    res=parseFloat(res).toFixed(6);
    return res;
  }  
  //3位小数 校验
  checkNumber = (value, number) => {
    let values =
      ('' + value)
        .replace(/[^\d\.]+/g, '')
        .replace(/\s/g, '')
        .replace(/^0+(\d)/, '$1')
        .replace(/^\./, '0.')
        .match(/^\d*(\.?\d{0,3})/g)[0] || '';
   return values
  }


  convertSG2GPS(sgLon, sgLat, callback) {
    if(process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt"){
      //i国网平台转换接口暂不支持，默认原数据返回
      var message = {
        success:true,
        resultData:{"longitude": sgLon, "latitude":sgLat},
        resultMsg:"i国网平台暂不支持转换",
      }
      callback(message); 
      return;
    }
    Toast.loading({
      duration: 0,
      message: "努力加载中...",
      forbidClick: true
    });
    console.log(" sgLon:" + sgLon + " sgLat:" + sgLat);
    if(sgLon && typeof sgLon === "string"){
      sgLon = parseFloat(sgLon);
    }
    if(sgLat && typeof sgLat === "string"){
      sgLat = parseFloat(sgLat);
    }
    
    var coordinatesArray = [];
    coordinatesArray.push([sgLon, sgLat]);
    Http.instance().postJSON({
      url: '/gmms-server/externalController',
      data: {
          route: '/gis/forward', 
          params: {
            "path":"/mapservice/spatial/shape/transfer",
            "transformType":"sg2cgcs",
            // "coordinates":"[[116.7937,25.202232],[116.729052,25.22119]]"   coordinates要转换的坐标对数组，坐标对数量不超过 1000
            "coordinates":JSON.stringify(coordinatesArray)
          },
      },
      autoShowWait: false,
      systemCode:"gmms_zs",
    }).then(result => {
      console.log("转换成功：", result);
      var content = result.content;
      Toast.clear();
      if(content["success"] == true){
        var message = {
          success:true,
          resultData:{"longitude": content["resultValue"][0][0], "latitude":content["resultValue"][0][1]},
          resultMsg:content["message"],
        }
        callback(message); 
      }else {
        var message = {
          success:false,
          resultData:content["resultValue"],
          resultMsg:content["message"],
        }
        callback(message); 
      }
    }).catch((err)=>{
      console.log("转换失败：", err);
      var message = {
        resultValue:false,
        resultData:err,
        resultMsg:err,
      }
      Toast.clear();
      callback(message);
    }) 

  }
}